﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Cinser.Common;
using System.Xml;
using Cinser.DataTranslate.SettingManager;

namespace Cinser.DataTranslate.TaskManager
{
    public class ImportTask:TaskBase
    {
        ImportSettings settings;
        DBTransplantation dbTrans;

        public ImportTask(SettingBase settings)
        {
            this.TaskName = "数据导入";
            this.settings = settings as ImportSettings;
        }

        public override void Execute()
        {
            Execute(new Action(() =>
            {
                ImportUnit();
                ImportProject();
                ImportDrill();
            }));
        }

        public void Execute(Action work)
        {
            this.BeginDate = DateTime.Now;
            this.Reset();

            TranslateDalBase sourceDal = new AccessTranslateDal(this.settings.SourceDataPath + "/database/DZZK.mdb", this.settings.SourceDbPassword);
            TranslateDalBase targetDal = new SdeTranslateDal(this.settings.Sde.Name, this.settings.Sde.UserName, this.settings.Sde.Password, this.settings.Sde.Ip, this.settings.Sde.ServerName, this.settings.Sde.Version);
            dbTrans = new DBTransplantation(sourceDal, targetDal);
            dbTrans.SendMessage = (msg) =>
            {
                this.AddTaskMsg(msg);
            };

            this.Subtitle = "准备转移数据";
            this.Introduce = "该操作包括验证数据库、及Ftp的连接是否正确。";

            if (sourceDal.CanConnected == false)
            {
                AddTaskMsg(new Cinser.Common.Model.Message("源数据库连接属性配置错误，请重新配置后再做导入操作。", Cinser.Common.Model.Message.MessageType.Error));
                this.ErrorNum++;
            }
            else if (targetDal.CanConnected == false)
            {
                AddTaskMsg(new Cinser.Common.Model.Message("目标数据库连接属性配置错误，请重新配置后再做导入操作。", Cinser.Common.Model.Message.MessageType.Error));
                this.ErrorNum++;
            }
            else
            {
                if (work != null)
                {
                    work();
                }
            }
            AddTaskMsg(new Cinser.Common.Model.Message("所有任务全部完成。", Cinser.Common.Model.Message.MessageType.Info));
            this.FinishDate = DateTime.Now;
            base.FireTaskComplate();
        }
        
        private void Test()
        {
            this.Subtitle = "正在转移测试数据";
            this.Introduce = "该操作包括转移A_TEST数据至A_TEST表，以及项目相关的文件数据至" + this.settings.Ftp.FtpUrl;
            string dbSourceConnectionStr = Cinser.DBUtility.Common.CombineConnectionString("192.168.1.40", "dzzh", "drill", "drill");
            string dbTargetConnectionStr = Cinser.DBUtility.Common.CombineConnectionString("192.168.1.40", "dzzh", "bjdzzh", "bjdzzh");
            dbTrans = new DBTransplantation(new OracleTranslateDal(dbSourceConnectionStr), new OracleTranslateDal(dbTargetConnectionStr));
            dbTrans.SendMessage = (msg) =>
            {
                this.AddTaskMsg(msg);
            };

            TranslateTableSettings test = new TranslateTableSettings("A_TEST", this);
            test.KeysColumns.Add("ID");    
            dbTrans.Translate(test);
        }

        private void ImportUnit(string sqlWhere="1=1")
        {
            this.Subtitle = "正在转移保管单位数据";
            this.Introduce = "该操作包括转移01BaoGuanDanWei数据至unit表，以及项目相关的文件数据至" + this.settings.Ftp.FtpUrl;

            TranslateTableSettings tableSettings = new TranslateTableSettings("01BaoGuanDanWei", this);
            tableSettings.TargetTbName = "unit";
            tableSettings.KeysColumns.Add("CUID");
            tableSettings.ColumnsMapping.Add("A", "B");

            tableSettings.BeforeAddOrUpdate = (dt) =>
            {
                Cinser.Common.Model.Message msg = null;
                dt.Columns.Add("X");
                dt.Columns.Add("Y");
                return msg;
            };

            tableSettings.AddOrUpdating = (dr) =>
            {
                Cinser.Common.Model.Message msg = null;
                //可对该行数据进行验证等操作。
                dr["X"] = 5;
                dr["Y"] = 5;

                return msg;
            };

            tableSettings.AddOrUpdated = (dr, ex) =>
            {
                Cinser.Common.Model.Message msg = null;

                return msg;
            };

            dbTrans.Translate(tableSettings, sqlWhere);
        }

        private void ImportProject(string sqlWhere = "1=1")
        {
            this.Subtitle = "正在转移项目数据";
            this.Introduce = "该操作包括转移02XiangMu数据至project表，以及项目相关的文件数据至" + this.settings.Ftp.FtpUrl;

            TranslateTableSettings tableSettings = new TranslateTableSettings("02XiangMu", this);
            tableSettings.TargetTbName = "project";
            tableSettings.KeysColumns.Add("ID");
            tableSettings.ColumnsMapping.Add("XMID", "ID");

            tableSettings.BeforeAddOrUpdate = (dt) =>
            {
                Cinser.Common.Model.Message msg = null;
                dt.Columns.Remove("ID");
                dt.Columns.Add("X");
                dt.Columns.Add("Y");
                return msg;
            };

            tableSettings.AddOrUpdating = (dr) =>
            {
                Cinser.Common.Model.Message msg = null;
                //可对该行数据进行验证等操作。
                dr["X"] = 5;
                dr["Y"] = 5;
                return msg;
            };

            tableSettings.AddOrUpdated = (dr, ex) =>
            {
                Cinser.Common.Model.Message msg = null;

                return msg;
            };

            dbTrans.Translate(tableSettings,sqlWhere);
        }

        private void ImportDrill(string sqlWhere = "1=1")
        {
            this.Subtitle = "正在转移项目数据";
            this.Introduce = "该操作包括转移03ZuanKongZhongYao数据至Drill表，以及项目相关的文件数据至" + this.settings.Ftp.FtpUrl;

            TranslateTableSettings tableSettings = new TranslateTableSettings("03ZuanKongZhongYao", this);
            tableSettings.TargetTbName = "Drill";
            tableSettings.KeysColumns.Add("ID");
            tableSettings.ColumnsMapping.Add("ZKID", "ID");

            tableSettings.BeforeAddOrUpdate = (dt) =>
            {
                Cinser.Common.Model.Message msg = null;
                dt.Columns.Remove("ID");
                dt.Columns.Add("X");
                dt.Columns.Add("Y");
                return msg;
            };

            tableSettings.AddOrUpdating = (dr) =>
            {
                Cinser.Common.Model.Message msg = null;
                //可对该行数据进行验证等操作。
                dr["X"] = 5;
                dr["Y"] = 5;
                return msg;
            };

            tableSettings.AddOrUpdated = (dr, ex) =>
            {
                Cinser.Common.Model.Message msg = null;

                return msg;
            };

            dbTrans.Translate(tableSettings,sqlWhere);
        }

        public override void Save()
        {
            if (TotalTaskCount != 0)
                TotalTaskFinishPercent = 100 - (ErrorNum / TotalTaskCount * 100f);
            TaskSetting s = new TaskSetting(Id, TaskName, LogId, settings.Id, BeginDate,
                FinishDate, TotalTaskCount, ErrorNum,TotalTaskFinishPercent );
            s.SaveSettings();
        }

        public override void Stop()
        {
            throw new NotImplementedException();
        }

        public override void Continue()
        {
            throw new NotImplementedException();
        }

        public override TaskBase Read(string id)
        {
            throw new NotImplementedException();
        }

        public override void Repair()
        {
            Execute(new Action(() =>
            {
                if (System.IO.File.Exists(this.LogPath))
                {
                    string[] logs = System.IO.File.ReadAllLines(this.LogPath);
                    //记录一个新Log
                    this.LogId = "";

                    if (logs != null && logs.Length > 0)
                    {
                        foreach (var item in logs)
                        {
                            if (item.IndexOf("[data:") != -1)
                            {
                                string[] arr = item.SubString("[data:", "]").Split('&');
                                if (arr != null && arr.Length == 2)
                                {
                                    string tbName = arr[0];
                                    string sqlWhere = arr[1];
                                    if (tbName == "01BaoGuanDanWei")
                                    {
                                        ImportUnit(sqlWhere);
                                    }
                                    else if (tbName == "02XiangMu")
                                    {
                                        ImportProject(sqlWhere);
                                    }
                                    else if (tbName == "03ZuanKongZhongYao")
                                    {
                                        ImportDrill(sqlWhere);
                                    }
                                }
                            }
                            else if (item.IndexOf("[file:") != -1)
                            {
                                string filePath = item.SubString("[file:", "]");
                                //传文件
                            }
                        }
                    }
                }
            }));
        }
    }
}
